import os
import ddddocr
import requests
from PIL import Image
import base64
from io import BytesIO
from utils.http_requester import HttpRequester
from utils.get_keywords import GetKeywords


# 因为登陆失败是因为验证码的问题导致的，所有对登陆失败重试是达不到效果的，所以把整个获取验证码的逻辑作为一个预处理器


def get_auth_captcha():
    payload = {
        "method": "get",
        "url": os.environ["URL"] + "/api/auth/captcha",
        # "url": "http://192.168.10.164:5173" + "/api/auth/captcha",
    }
    response = requests.request(**payload).json()
    sn = GetKeywords.get_keyword(response, "sn")
    image = GetKeywords.get_keyword(response, "image")
    return sn, image


def dddd_ocr_text():
    """
    进行OCR识别的函数
    :return: 识别之后的文本
    """
    sn, data = get_auth_captcha()
    # data = get_auth_captcha()[1]
    # 分割data文本，得到头部信息和 Base64编码部分
    encode_data = data.split(",")[1]

    # 解码 Base64 元数据
    decode_data = base64.b64decode(encode_data)

    # 把解码数据调整为图像数据
    image = Image.open(BytesIO(decode_data))

    # 把图像数据转成字节数据
    image_bytes = BytesIO()
    image.save(image_bytes, format="PNG")
    image_bytes = image_bytes.getvalue()

    # 初始化
    ocr = ddddocr.DdddOcr()
    text = ocr.classification(image_bytes)
    return sn, text


# 用于存下全局的验证码和sn
sn_text = {}
# 用于表示 次数和失败重试的代码
run_nums = 0


def get_res_sn_text():
    """调用识别sn和验证码"""
    global run_nums
    if not sn_text or run_nums % 2 == 0:
        sn, text = dddd_ocr_text()
        sn_text["sn"] = sn
        sn_text["text"] = text

    run_nums += 1
    return sn_text

# if __name__ == '__main__':
#     data = ""
#     print(dddd_ocr_text(data))
